package cn.itcast.service.impl;

import cn.itcast.pojo.Weather;
import cn.itcast.service.WeatherService;
import cn.itcast.utils.CityCodeUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private RestTemplate restTemplate;
    /**
     *
     * @param cityName 城市名称
     * @return 5天的城市天气信息
     */
    @Override
    public List<Weather> getCityWeatherInfo(String cityName) {
        String cityCode = CityCodeUtils.getCityCode(cityName);
        String forObject = restTemplate.getForObject("http://t.weather.itboy.net/api/weather/city/"
                                                    + cityCode, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        Object data = jsonObject.get("data");
        Object forecast = ((JSONObject) data).get("forecast");
        JSONArray jsonArray = (JSONArray) forecast;
        List<Weather> javaList = jsonArray.toJavaList(Weather.class);
        return javaList;
    }
}
